<template>
  <!-- 关键词页面 -->
  <div>
    <div class="box">
      <!-- 头部 -->
      <div class="header">
        <el-input
          v-model="input"
          placeholder="请输入关键字"
          class="elinput"
        ></el-input>
        <el-input
          v-model="input2"
          placeholder="请输入跳转链接"
          class="elinput"
        ></el-input>
        <el-button type="primary" @click="sele">查找</el-button>
        <el-button type="primary" @click="append">添加</el-button>
        <el-button type="primary" @click="derive">导出</el-button>
      </div>
      <!-- 身体 -->
      <div class="bottom">
        <!-- 内容 -->
        <template>
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column
              label="关键词ID"
              width="180"
              prop="id"
              sortable
              align="center"
            >
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column label="关键词" width="180" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.keyword }}</span>
              </template>
            </el-table-column>
            <el-table-column label="跳转链接" width="180" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.url }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否推荐" width="180" align="center">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium" v-if="scope.row.isHot == true"
                      >是</el-tag
                    >
                    <el-tag size="medium" v-if="scope.row.isHot == false"
                      >否</el-tag
                    >
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="是否默认" width="180" align="center">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium" v-if="scope.row.isDefault == true"
                      >是</el-tag
                    >
                    <el-tag size="medium" v-if="scope.row.isDefault == false"
                      >否</el-tag
                    >
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 分页 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
          >
          </el-pagination>
        </div>
        <!-- 添加编辑模态框 -->
        <el-dialog title="创建" :visible.sync="dialogFormVisible">
          <el-form :model="form" :rules="rules" ref="form">
            <el-form-item
              label="关键词"
              :label-width="formLabelWidth"
              prop="name"
            >
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="跳转链接"
              :label-width="formLabelWidth"
              prop="date1"
            >
              <el-input v-model="form.date1" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="是否推荐"
              :label-width="formLabelWidth"
              prop="region"
            >
              <el-select v-model="form.region" placeholder="请选择活动区域">
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="是否默认"
              :label-width="formLabelWidth"
              prop="date2"
            >
              <el-select v-model="form.date2" placeholder="请选择活动区域">
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              type="primary"
              v-if="flag == 1"
              @click="submitForm('form', 1)"
              >确 定</el-button
            >
            <el-button
              type="primary"
              v-if="flag == 2"
              @click="submitForm('form', 2)"
              >修改</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import { getList, add, revise, dele } from "@/api/scgl/keyword";
export default {
  data() {
    return {
      input: "",
      input2: "",
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
        },
      ],
      total: 0,
      currentPage4: 1,
      pageNum: 10,
      //添加编辑模态框
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
      },
      formLabelWidth: "120px",
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        date1: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        region: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],

        date2: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
      },
      edit: "",
      flag: 1,
    };
  },
  methods: {
    //表格
    handleEdit(index, row) {
      console.log(index, row);
      this.edit = row;
      this.flag = 2;
      this.dialogFormVisible = true;
      this.form.name = row.id;
      this.form.date1 = row.url;
      this.form.region = row.isHot;
      this.form.date2 = row.isDefault;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        dele({
          addTime: row.addTime,
          deleted: row.deleted,
          id: row.id,
          isDefault: row.isDefault,
          isHot: row.isHot,
          keyword: row.keyword,
          sortOrder: row.sortOrder,
          updateTime: row.updateTime,
          url: row.url,
        }).then((res) => {
          //console.log(res);
          if (res.errmsg == "成功") {
            getList({
              page: this.currentPage4,
              limit: this.pageNum,
              sort: "add_time",
              order: "desc",
            }).then((res) => {
              if (res.errmsg == "成功") {
                //console.log(res);
                this.tableData = res.data.list;
                this.total = res.data.total;
              }
            });
          }
        });
      });
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = val;
      getList({
        page: this.currentPage4,
        limit: this.pageNum,
        sort: "add_time",
        order: "desc",
      }).then((res) => {
        if (res.errmsg == "成功") {
          //console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val;
      getList({
        page: this.currentPage4,
        limit: this.pageNum,
        sort: "add_time",
        order: "desc",
      }).then((res) => {
        if (res.errmsg == "成功") {
          //console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    sele() {
      getList({
        page: this.currentPage4,
        limit: this.pageNum,
        keyword: this.input,
        url: this.input2,
        sort: "add_time",
        order: "desc",
      }).then((res) => {
        if (res.errmsg == "成功") {
          //console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    //导出
    derive() {
      const tableData = this.tableData; // 如果表格数据为空，提示

      if (tableData.length === 0) {
        this.$message({
          type: "warning",
          message: "没有数据可以导出！",
        });
        return;
      } // 定义表头

      const headers = [
        "关键词ID",
        "关键词",
        "跳转链接",
        "是否推荐",
        "是否默认",
      ]; // 将表格数据转换为工作表数据

      const worksheetData = [
        headers, // 第一行为表头
        ...tableData.map((item) => [
          item.id || "暂无", // 如果为空，填充为“暂无”
          item.keyword || "暂无",
          item.url || "暂无",
          item.isHot || "暂无",
          item.isDefault || "暂无",
        ]),
      ]; // 创建工作表

      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData); // 创建工作簿

      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1"); // 导出 Excel 文件

      XLSX.writeFile(workbook, "数据列表.xlsx"); // 提示导出成功

      this.$message({
        type: "success",
        message: "导出成功！",
      });
    },
    append() {
      this.dialogFormVisible = true;
      this.form.name = "";
      this.form.date1 = "";
      this.form.region = "";
      this.form.date2 = "";
      this.flag = 1;
    },
    submitForm(formName, a) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (a == 1) {
            add({
              keyword: this.form.name,
              url: this.form.date1,
              isHot: this.form.region,
              isDefault: this.form.date2,
            }).then((res) => {
              if (res.errmsg == "成功") {
                this.$message({
                  type: "success",
                  message: "添加成功",
                });
                this.dialogFormVisible = false;
                getList({
                  page: this.currentPage4,
                  limit: this.pageNum,
                  sort: "add_time",
                  order: "desc",
                }).then((res) => {
                  if (res.errmsg == "成功") {
                    //console.log(res);
                    this.tableData = res.data.list;
                    this.total = res.data.total;
                  }
                });
              }
            });
          } else {
            revise({
              addTime: this.edit.addTime,
              deleted: this.edit.deleted,
              id: this.edit.id,
              isDefault: this.form.date2,
              isHot: this.form.region,
              keyword: this.form.name,
              sortOrder: this.edit.sortOrder,
              updateTime: this.edit.updateTime,
              url: this.form.date1,
            }).then((res) => {
              console.log(res);
              if (res.errmsg == "成功") {
                this.$notify({
                  title: "成功",
                  message: "修改成功",
                  type: "success",
                });
                getList({
                  page: this.currentPage4,
                  limit: this.pageNum,
                  sort: "add_time",
                  order: "desc",
                }).then((res) => {
                  if (res.errmsg == "成功") {
                    //console.log(res);
                    this.tableData = res.data.list;
                    this.total = res.data.total;
                  }
                });
                this.dialogFormVisible = false;
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    getList({
      page: this.currentPage4,
      limit: this.pageNum,
      sort: "add_time",
      order: "desc",
    }).then((res) => {
      if (res.errmsg == "成功") {
        //console.log(res);
        this.tableData = res.data.list;
        this.total = res.data.total;
      }
    });
  },
};
</script>

<style scoped>
.header {
  display: flex;
}
.elinput {
  width: 200px;
}
</style>